package com.heu.blood.security.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heu.blood.common.utils.JwtUtil;
import com.heu.blood.security.dto.req.SpecialLoginReqDTO;
import com.heu.blood.security.dto.resp.SpecialLoginRespDTO;
import com.heu.blood.security.entity.BloodRoleEntity;
import com.heu.blood.security.entity.LoginUser;
import com.heu.blood.security.entity.UserEntity;
import com.heu.blood.security.service.BloodRoleService;
import com.heu.blood.security.service.LoginService;
import com.heu.blood.security.service.UserRoleService;
import com.heu.blood.security.service.UserService;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private Cache userCache;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private UserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private BloodRoleService bloodRoleService;


    @Override
    public Map<String,Object> login(UserEntity user) {
        // AuthenticationManager authenticationManager 进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //如果认证没通过，给予相应提示
        if (Objects.isNull(authenticate)){
            throw new RuntimeException("登录失败");
        }
        // 如果认证通过了，使用userId生成jwt jwt存入ResponseResult
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        // 获取用户对应的权限信息
        List<String> permissions = loginUser.getPermissions();
        // 获取用户对应的角色信息
        List<Long> roleIds = userRoleService.getRoleByUser(Long.valueOf(userId));
        String jwt = JwtUtil.createJWT(userId);
        Map<String,Object> map = new HashMap<>();
        map.put("token", jwt);
        map.put("permissions", permissions);
        map.put("roleIds", roleIds);
        // 登陆成功后把信息录入到结果里面
        UserEntity userRes = loginUser.getUser();
        map.put("userMsg",userRes);
        // 将loginUser存入到userCache中
        userCache.put("login:"+userId, loginUser);
        userCache.put("login_time:" + userId, System.currentTimeMillis());
        LambdaQueryWrapper<BloodRoleEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BloodRoleEntity::getRoleCode,userRes.getUserType());
        BloodRoleEntity roleRes = bloodRoleService.getOne(queryWrapper);
        map.put("roleRes",roleRes);
        return map;
    }


    @Override
    public void logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getUser().getId();
        // 将loginUserUserCache中删除
        userCache.evictIfPresent("login:"+userId);
        userCache.evictIfPresent("login_time:" + userId);
    }

    /**
     * 用户注册
     * @return
     */
    @Override
    public Pair<Boolean, String> register(UserEntity userEntity) {
        Integer duplicateUserNameCount = userService.userNameDuplicateCheck(userEntity.getUserName());
        boolean result = (duplicateUserNameCount == 0); // 能否注册成功
        String msg = result ? "注册成功！" : "用户名已被注册，可更换为" + userEntity.getUserName() + String.format("%02d", duplicateUserNameCount + 1);

        if (result) {
            // 用户名未被注册，则对密码进行加密
            String encodedPassword = passwordEncoder.encode(userEntity.getPassword());

            // 设置新用户的用户名和加密后的密码
            UserEntity newUser = new UserEntity();
            newUser.setUserName(userEntity.getUserName());
            newUser.setPassword(encodedPassword);

            // 保存新用户信息
            userService.save(newUser);
        }

        return Pair.of(result, msg);
    }

    @Override
    public SpecialLoginRespDTO specialLogin(SpecialLoginReqDTO requestParam) {
        // AuthenticationManager authenticationManager 进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(requestParam.getUserName(), requestParam.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //如果认证没通过，给予相应提示
        if (Objects.isNull(authenticate)){
            throw new RuntimeException("登录失败");
        }
        // 如果认证通过了，使用userId生成jwt jwt存入ResponseResult
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        // 获取用户对应的权限信息
        List<String> permissions = loginUser.getPermissions();
        // 获取用户对应的角色信息
        List<Long> roleIds = userRoleService.getRoleByUser(Long.valueOf(userId));
        SpecialLoginRespDTO specialLoginRespDTO = SpecialLoginRespDTO.builder()
                .permissions(loginUser.getPermissions())
                .roleIds(roleIds)
                .build();
        return specialLoginRespDTO;
    }
}
